package com.lhdx.practical.controllers;

import com.alibaba.fastjson.JSONObject;
import com.lhdx.practical.bean.Person;
import com.lhdx.practical.service.PersonService;
import com.lhdx.practical.utils.Constants;
import com.lhdx.practical.utils.CookieUtils;
import com.lhdx.practical.utils.JsonUtils;
import com.lhdx.practical.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Controller
public class LoginController {
    @Autowired
    private PersonService personService;

    @GetMapping("/")
    public ModelAndView login() {
        return new ModelAndView("login");
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @CrossOrigin
    @PostMapping("/tologin")
    @ResponseBody
    public String tologin(HttpServletRequest request, HttpServletResponse response, String username, String password, String tCode){
        JSONObject jsonObject = new JSONObject();
        try {
            String strNum = request.getSession().getAttribute("checkCode")+"";
            if(tCode.equals(strNum)){
                Person person = personService.findByUsernameAndPassword(username,Md5Utils.md5(password));
                if(person == null){
                    jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"用户名密码错误","");
                }else{
                    //更新登录时间
                    personService.updateLoginTime(person.getId(),new Date().getTime());
                    //保存用户ID到cookie
                    CookieUtils.setcookie(response, Constants.LOGINED, String.valueOf(person.getId()));
                    //清楚登录验证码cookie
                    CookieUtils.removeVerCookie(response);
                    jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"登录成功","");
                }
            }else{
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"验证码错误","");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"登录失败","");
        }
        return jsonObject.toString();
    }

}

